package com.edais.service.imp;

import com.edais.actions.PerMatchDetailAction;
import com.edais.dao.CaptchaDao;
import com.edais.domain.MobileValidate;
import com.edais.service.CaptchaService;
import com.edais.util.*;
import com.edais.util.RSAThirdParty.RSA;
import com.umpay.api.util.StringUtil;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service

@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public class CaptchaServiceImp implements CaptchaService {
	private static final Log logger = LogFactory.getLog(PerMatchDetailAction.class);

	@Autowired
	private CaptchaDao captchaDao;

	/**
	 * 获取验证码
	 * @param userId 用户id
	 * @param type 类型
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public ResultDTO getCaptcha(HttpSession session, String userId, String type) throws Exception{
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String randomCode = "";
		String description = "";
		boolean flag = false;
		
		String mobile = this.captchaDao.getMobileById(userId);
		if (StringUtil.isEmpty(mobile)) {
			return ResultConstant.NOT_MOBILE;
		}
		
		// 校验手机号是否合法
		if (!mobile.matches(Consts.PHONECHECK)) {
			logger.debug("/captcha/getCaptcha 用户已绑定手机格式不对！手机号：" + mobile);
			return ResultConstant.FAILED;
		}

		// 设置汇款卡号
		if ("RECEPAY_CARD".equals(type)) {
			description = "设置回款卡号";
		// 修改密码
		} else if ("MODIFY_PASSWORD".equals(type)) {
			description = "修改密码";
		}
		//修改手机(MODIFY_MOBILE)
		else if ("MODIFY_MOBILE".equals(type)) {
			// 绑定的手机号是否已注册
//			int count = usersDao.phoneIsExisted(mobile);
//			if (count > 0) {
//				rtnMap.put("rescode", Consts.CHECK_CODE);
//				rtnMap.put("resmsg",  "mobile.is.bound");//选择绑定的手机号码已注册过账户
//				logger.debug("/captcha/getCaptcha 选择绑定的手机号码已注册过账户！手机号：" + mobile);
//				return rtnMap;
//			}else{
//				description = "修改绑定手机";
//			}
			description = "修改绑定手机";
		}
		
		// 先判断是否已获取验证码（10分钟内有效）
		//获取手机号信息
		ArrayList randomCodeArray = (ArrayList) session.getAttribute(mobile);
		Date now = new Date();
		
		if (randomCodeArray != null && randomCodeArray.size() > 0) {
			// 验证码存在,进行时间判断
			Date codeTime = (Date) randomCodeArray.get(2);
			Date codeTime_10 = new Date(codeTime.getTime() + 600000);// 10分钟后的时间
			
			if (now.getTime() > codeTime_10.getTime()) {
				// 超过10分钟，无效,清除session
				session.removeAttribute(mobile);
				// 获取随机验证码:随机产生的6位数字
				randomCode = CommonUtil.getRandomCode();
				flag = true;
			} else {
				randomCode = (String) randomCodeArray.get(1);
			}
		} else {
			// 获取随机验证码:随机产生的6位数字
			randomCode = CommonUtil.getRandomCode();
			flag = true;
		}
		
		//(手机)短信系统 工具
		logger.debug("手机号：" + mobile + "验证码："+ randomCode);
		
		//(手机)短信系统 工具
		SanTongSmsUtil smsUtil = new SanTongSmsUtil();
		// 发送短信
		Map<String, String> map = new HashMap<String, String>();
		map.put("0", description);
		map.put("1", randomCode);
		
		// 获取短信模版
		String conent = smsUtil.tSmsContent("tel_check", map);
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String,String>();
		paramMap.put("content", conent);
		paramMap.put("mobileListParams", mobile);
//		String param = CommonUtil.getHttpParameterFromMap(paramMap);
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if(StringUtils.isBlank(smsResult)){
			//失败
			return ResultConstant.FAILED;
		}else{
			//解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if(null == smsResultMap  || "sysException".equals(smsResultMap.get("rescode"))){
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				//失败
				return ResultConstant.FAILED;
			}else if( "BusinessException".equals(smsResultMap.get("rescode"))){
				//业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				return ResultConstant.FAILED;
			}
		}
		
		// 保存验证码到缓存（手机号+验证码+生成时间）
		if (flag) {
			ArrayList<Object> newRandomCodeArray = new ArrayList<Object>();
			newRandomCodeArray.add(0, mobile);//手机号
			newRandomCodeArray.add(1, randomCode);//
			newRandomCodeArray.add(2, now);
			session.setAttribute(mobile, newRandomCodeArray);//以当前手机号为key，将相关信息放入session中
			
			// 保存验证码到DB
			try{
				this.saveRandomCode(mobile,randomCode,type);
			}catch (Exception e) {
				logger.error("/captcha/getCaptcha 验证码保存失败，失败原因：" + e.getCause());
			}
		}
		ResultDTO<String> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
		resultDTO.setRecord(mobile);
		return resultDTO;
	}
	
	// 保存验证码到DB
	private void saveRandomCode(String mobileNum, String randomCode, String type) throws Exception{
		Date now = new Date();
		Date lostTime = new Date(now.getTime() + 600000);// 10分钟后的时间
		
		MobileValidate mobileValidate = new MobileValidate();
		mobileValidate.setCreate_time(now);
		mobileValidate.setEnable('Y');
		mobileValidate.setLost_time(lostTime);
		mobileValidate.setMobile(mobileNum);
		mobileValidate.setRandom_char(randomCode);
		mobileValidate.setValidate_char(randomCode);
		mobileValidate.setValidate_type(type);
		
		this.captchaDao.saveRandomCode(mobileValidate);
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 根据用户id获取用户手机号
	 */
	@Override
	public String getMobileById(String userId) throws Exception {
		return this.captchaDao.getMobileById(userId);
	}
}
